package com.gooluke.mds.aspect;

import com.gooluke.mds.datasource.MultiDataSourceContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author gooluke
 * description
 * datetime 2025-06-11 19:41
 */
@Aspect
@Component
@Slf4j
public class MapperAspect {

    /**
     * 注解加在方法上
     */
    @Pointcut("@annotation(org.apache.ibatis.annotations.Mapper)")
    private void methodPointCut() {}

    /**
     * 注解加在类上
     */
    @Pointcut("@within(org.apache.ibatis.annotations.Mapper)")
    public void classPointcut() {}

    @Around(value = "methodPointCut() || classPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //如果没有开启多数据源，则直接执行
        if (!MultiDataSourceContext.enabled()) {
            return joinPoint.proceed();
        }
        Object result = null;
        List<String> dataSourceNames = MultiDataSourceContext.getDataSourceNames();
        try {
            for (String dataSourceName : dataSourceNames) {
                MultiDataSourceContext.checkTransaction(dataSourceName);
                result = joinPoint.proceed();
            }
            return result;
        } catch (Exception e) {
            log.error("执行异常：", e);
            throw new RuntimeException(e);
        }
    }

}
